package org.jactao.remote.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.jactao.serialization.LSerializer;

/**
 * Created by fanzetao on 2018/4/3.
 */
public class NettyDecoder extends LengthFieldBasedFrameDecoder {

    private LSerializer serializer;

    public NettyDecoder serializer(LSerializer serializer) {
        this.serializer = serializer;
        return this;
    }

    public NettyDecoder(int maxFrameLength) {
        super(maxFrameLength, 0, 2, 0, 2);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf decode = (ByteBuf) super.decode(ctx, in);
        if (decode != null) {
            int length = decode.readableBytes();
            byte[] content = new byte[length];
            decode.readBytes(content);
            return serializer.deserialize(content);
        }
        return null;
    }
}
